package webapi

import (
	"strings"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/google/uuid"
	"github.com/wonderivan/logger"
)

//ClientMqttAPI **
type ClientMqttAPI struct {
	mqttClient mqtt.Client
	isClosed   bool
	key        string
	topicPub   string
	topicSub   string
}

//Regist **
func (_this *ClientMqttAPI) Regist() {
	_this.key = "webapi-mqtt"
	//初始化MQTT
	addr := "tcp://0.0.0.0:000"

	opts := mqtt.NewClientOptions().AddBroker(addr).SetClientID("webapi" + strings.Replace(uuid.NewString(), "-", "", -1))

	//set userName
	opts.SetKeepAlive(2 * time.Second)
	opts.SetPingTimeout(1 * time.Second)

	opts.SetOnConnectHandler(func(cc mqtt.Client) {
		logger.Debug(_this.key + " : Connect")
		_this.mqttClient = cc
		//_this.mqttClient.
		//subscribe topic
		/*for _, pare := range _this.mqttCSPares {
			pare.SetMqttClient(cc)
			pare.SubMessage()
		}*/
		//_this.subMessage()
	})
	opts.SetConnectionLostHandler(func(_ mqtt.Client, _ error) {
		_this.mqttClient = nil
		/*for _, pare := range _this.mqttCSPares {
			pare.SetMqttClient(nil)
		}*/
		logger.Debug(_this.key + " : LostConnect")
	})

	c := mqtt.NewClient(opts)
	token := c.Connect()
	waitRes := token.WaitTimeout(time.Second * 5)
	waitErr := token.Error()
	for !waitRes || waitErr != nil {
		if _this.isClosed {
			logger.Debug(_this.key + ": CLOSE")
			return //true
		}
		if waitErr != nil {
			logger.Debug(_this.key + ": " + waitErr.Error())
		} else {
			logger.Debug(_this.key + ": " + "MQTT连接超时")
		}
		waitRes = token.WaitTimeout(time.Second * 5)
		waitErr = token.Error()
	}
	_this.mqttClient = c
	//订阅MQTT
	//对MQTT事件回应
}

//SubMessage 订阅消息
func (_this *ClientMqttAPI) SubMessage() {
	logger.Debug("sub:" + _this.topicSub)

	if token := _this.mqttClient.Subscribe(_this.topicSub, 0, _this.getMessageHandler); token.Error() != nil {
		logger.Alert("token.Error()")
		logger.Alert(token.Error().Error())
		token.Wait()
		//os.Exit(1)
	}
}

//SendData Fun
func (_this *ClientMqttAPI) SendData(buffer []uint8) bool {
	if _this.mqttClient != nil && _this.mqttClient.IsConnected() {
		connected := _this.mqttClient.IsConnected()
		if _this.mqttClient != nil && connected {
			logger.Debug("pub:" + _this.topicPub)
			_this.mqttClient.Publish(_this.topicPub, 0, false, buffer)
			return true
		}
		logger.Alert("pub error")
	}
	return false
}

func (_this *ClientMqttAPI) getMessageHandler(client mqtt.Client, message mqtt.Message) {
	/*if _this.receiver != nil {
		_this.receiver(_this.GetKey(), message.Payload())
	}*/
}
